package com.xudow.app.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.activeshare.edu.ucenter.models.base.OrderItems;
import com.activeshare.edu.ucenter.models.course.CourseWithOtherInfo;
import com.activeshare.edu.ucenter.models.order.OrderWithLineitems;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.model.MOrder;
import com.xudow.app.ui.adapter.OrderDetialAdapter;
import com.xudow.app.ui.adapter.OrderListAdapter;
import com.xudow.app.ui.task.OrderDeleteTask;
import com.xudow.app.ui.task.OrderDetailTask;
import com.xudow.app.ui.task.ShowOrderDetailTask;
import com.xudow.app.util.ImageUtils;

import java.util.HashMap;

import javax.security.auth.login.LoginException;


public class OrderDetailActivity extends BaseActivity implements View.OnClickListener,DialogInterface.OnClickListener, AdapterView.OnItemClickListener {
    private String orderId;//订单号
    private TextView schoolname,ordertype,cancel,pay;
    private TextView tv6,tv7,tv8,tv9;
    private ImageView schoolIco;
    private OrderWithLineitems mo;
    private ListView courseList;
    private int flage=0;//对话框标记
    private RelativeLayout bottomRy;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail_layout);
        orderId=getIntent().getStringExtra("orderId");
        //orderId="66465";
//        Log.e("onCreate: ","orderid:"+orderId );
        initView();
        initLisenter();
    }

    private void initLisenter() {
        courseList.setOnItemClickListener(this);
        cancel.setOnClickListener(this);
        pay.setOnClickListener(this);
    }

    private void initView() {
        courseList=(ListView)findViewById(R.id.course_listview);
        courseList.setDivider(null);
        schoolname=(TextView)findViewById(R.id.name);
        ordertype=(TextView)findViewById(R.id.order_type);
        schoolIco=(ImageView)findViewById(R.id.school_img);
        bottomRy=(RelativeLayout)findViewById(R.id.bottom_ry);
        cancel=(TextView)findViewById(R.id.cancel_tv);
        pay=(TextView)findViewById(R.id.pay_tv);
        tv6=(TextView)findViewById(R.id.tv_6);
        tv7=(TextView)findViewById(R.id.tv_7);
        tv8=(TextView)findViewById(R.id.tv_8);
        tv9=(TextView)findViewById(R.id.tv_9);

    }

    public void goBackClick(View view){
        finish();
    }
    //课程编号6951--学生编号:48434
    //"data":"66450"

    @Override
    protected void onStart() {
        super.onStart();
        initData();
    }

    private void initData() {
        HashMap<String,String> pramers=new HashMap<String, String>();
        pramers.put("order_id",orderId);
        OrderDetailTask task=new OrderDetailTask(getApplicationContext(),orderDetailHandler);
        addTask(task);
        task.execute(pramers);
        showLodingDialog("正在处理");
    }

    /**
     *
     * 订单详情Handler
     */
    private Handler orderDetailHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideLoadingDialog();
            if (msg.what== ShowOrderDetailTask.SUCCESS){
                mo=(OrderWithLineitems) msg.obj;
                if (null!=mo){
                    updataUI(mo);
                    OrderDetialAdapter myadapter=new OrderDetialAdapter(OrderDetailActivity.this,mo.getItems());
                    courseList.setAdapter(myadapter);

                }
            }else
                getMyApp().makeToast("订单获取失败");
        }
    };


    private void updataUI(OrderWithLineitems item) {
        CourseWithOtherInfo course= item.getItems().get(0).getCourse();
        if (null!=course.getAgencyName()&&!"null".equals(course.getAgencyName()))
            schoolname.setText(course.getAgencyName()+"("+course.getSchoolName()+")");
        else
            schoolname.setText(course.getTeacher()+"("+course.getSchoolName()+")");
            if (item.getStatus()==0) {
                ordertype.setText("待支付");
            }else if (item.getStatus()==1) {
                ordertype.setText("已支付");
                bottomRy.setVisibility(View.INVISIBLE);
            }else if (item.getStatus()==2){
                ordertype.setText("已过期");}

        tv6.setText(item.getTotalPrice()+"0");
        tv7.setText(item.getOrderSn());
        tv8.setText(getTime(item.getCreateTime().getTime()));
        if (null!=item.getPayTime())
            tv9.setText(getTime(item.getPayTime().getTime()));

    }

    /**
     * 时间戳转换
     * @param t
     * @return
     */
    private String getTime(long t){
        long splite=System.currentTimeMillis()-t;
        if (splite<MINI){
            return "1分钟前";
        }else if (MINI<splite&&splite<HOUR) {
            return splite / MINI + "分钟前";
        }else if (splite>HOUR&&splite<DAY){
            return splite/HOUR+"小时前";
        }else

        return  new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date(t));
    }
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.cancel_tv:
                dialog("取消订单，本单享有的优惠会一并取消。是否继续？",1);
                break;
            case R.id.pay_tv:
                //TODO 支付
                dialog("确认支付该订单",2);
                break;
            case R.id.course_layout:

                break;
        }
    }
    private final long MINI=1000*60+0L;
    private final long HOUR=MINI*60;
    private final long DAY=HOUR*24;

    /**
     * 对话框
     */
    protected void dialog(String title,int n) {
        flage=n;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(title);  builder.setTitle("提示");
        builder.setPositiveButton("确认", OrderDetailActivity.this);
        builder.setNegativeButton("取消", OrderDetailActivity.this);
        builder.create().show();
    }
    //取消-2 确认-1
    @Override
    public void onClick(DialogInterface dialog, int which) {
        Log.e("orderDetailActivity", "onClick: " + which);
        if (flage == 1) {
            if (which == -1) {
                HashMap<String, String> pramers = new HashMap<String, String>();
                pramers.put("order_id", orderId);
                OrderDeleteTask deleteTask= new OrderDeleteTask(getApplicationContext(), deletHandler);
                addTask(deleteTask);
                deleteTask.execute(pramers);
                showLodingDialog("正在取消订单");
            }
            dialog.dismiss();
        }
        if (flage == 2) {
            //TODO 支付请求
            if (-1 == which){
                Intent intent = new Intent(this, PayActivity.class);
                intent.putExtra("orderPrice", mo.getTotalPrice()+"");
                intent.putExtra("orderId", mo.getId());
                startActivity(intent);
            }
            dialog.dismiss();
        }
    }
    private Handler deletHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideLoadingDialog();
            if (msg.what==OrderDetailTask.SUCCESS){
                getMyApp().makeToast("成功取消订单");
                finish();
            }else
                getMyApp().makeToast("操作失败");
        }
    };

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }
}
